package com.ruoyi.quartz.service.impl;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import javax.annotation.PostConstruct;

import com.ruoyi.system.domain.SysSendTask;
import com.ruoyi.system.domain.SysSendTaskDetail;
import com.ruoyi.system.service.ISysSendTaskService;
import com.ruoyi.system.service.impl.SysSendTaskServiceImpl;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.mapper.SysJobMapper;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.quartz.util.ScheduleUtils;
import sun.rmi.log.LogInputStream;

/**
 * 定时任务调度信息 服务层
 * 
 * @author ruoyi
 */
@Service
public class SysJobServiceImpl implements ISysJobService
{
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobMapper jobMapper;

    @Autowired
    private ISysSendTaskService sysSendTaskService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException
    {
        scheduler.clear();
        List<SysJob> jobList = jobMapper.selectJobAll();
        for (SysJob job : jobList)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 获取quartz调度器的计划任务列表
     * 
     * @param job 调度信息
     * @return
     */
    @Override
    public List<SysJob> selectJobList(SysJob job)
    {
        return jobMapper.selectJobList(job);
    }

    /**
     * 通过调度任务ID查询调度信息
     * 
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public SysJob selectJobById(Long jobId)
    {
        return jobMapper.selectJobById(jobId);
    }

    /**
     * 暂停任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0)
        {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0)
        {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws SchedulerException
    {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = jobMapper.deleteJobById(jobId);
        if (rows > 0)
        {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     * 
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException
    {
        for (Long jobId : jobIds)
        {
            SysJob job = jobMapper.selectJobById(jobId);
            deleteJob(job);
        }
    }

    /**
     * 任务调度状态修改
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob job) throws SchedulerException
    {
        int rows = 0;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
        {
            rows = resumeJob(job);
        }
        else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
        {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(SysJob job) throws SchedulerException
    {
        boolean result = false;
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getJobId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 新增任务
     * 
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJob job) throws SchedulerException, TaskException
    {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insertJob(job);
        if (rows > 0)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(SysJob job) throws SchedulerException, TaskException
    {
        SysJob properties = selectJobById(job.getJobId());
        int rows = jobMapper.updateJob(job);
        if (rows > 0)
        {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * 更新任务
     * 
     * @param job 任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException
    {
        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 校验cron表达式是否有效
     * 
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression)
    {
        return CronUtils.isValid(cronExpression);
    }

    @Override
    public boolean doSendTask() throws Exception {
        List<String> userList=new ArrayList<>();
        //用户 所有的群---key 成员名称  value 可发送群编号
        Map<String,List<String>> userAllWxGroupMap=new HashMap<>();
        //用户中  是被邀请的群
        Map<String,List<String>> userApplyWxGroupMap=new HashMap<>();


        //群  活跃级别   key 群名称  value 群活跃等级
        Map<String,String> wxgroupLevelMap=new HashMap<>();

        //群发送记录--key 成员名称   vue为需要
        Map<String, Map<String, Date>  > sendRecordMap=new HashMap<>();

        // 1.获取员工集合
        List<Map<String, Object>> queryUserList=jdbcTemplate.queryForList(" select   dict_value from sys_dict_data where status = '0' and dict_type = 'wx_group_number' order by dict_sort asc");
        if (queryUserList!=null&&queryUserList.size()>0){
            for (int i=0;i<queryUserList.size();i++){
                String userName=queryUserList.get(i).get("dict_value").toString();
                userList.add(userName);
            }
        }
        //2.获取所有员工的群
        for (int i=0;i<userList.size();i++){
            String userName=userList.get(i);
            //加群5天后  才可发送
            List<Map<String, Object>> queryUserWxgroupList=jdbcTemplate.queryForList(" select group_number,gruop_level   from sys_wx_group  WHERE    attribute1='0'   and FIND_IN_SET('"+userName+"',member)  and  create_time <date_sub(now(), interval 7 day) \n");
            List<String> wxgroupnameList=new ArrayList<>();
            if (queryUserWxgroupList!=null&&queryUserWxgroupList.size()>0){
                for (int j=0;j<queryUserWxgroupList.size();j++){
                    wxgroupnameList.add(queryUserWxgroupList.get(j).get("group_number").toString().trim());
                    if (!wxgroupLevelMap.containsKey(queryUserWxgroupList.get(j).get("group_number").toString().trim())){
                        wxgroupLevelMap.put(queryUserWxgroupList.get(j).get("group_number").toString().trim(),
                                queryUserWxgroupList.get(j).get("gruop_level").toString().trim());

                    }
                }
            }
            userAllWxGroupMap.put(userName,wxgroupnameList);
        }
        //3.获取每个员工被邀请   加入的群聊
        List<Map<String, Object>> queryApplyWxgroupList=jdbcTemplate.queryForList(" select  member,group_number   from sys_wxapply_record  WHERE    attribute1 is not null   and status=0  ");
         if (queryApplyWxgroupList!=null&&queryApplyWxgroupList.size()>0){
            for (int i=0;i<queryApplyWxgroupList.size();i++){
                Map<String, Object> result=queryApplyWxgroupList.get(i);
                String username= (String) result.get("member");
                if (userApplyWxGroupMap.containsKey(username.trim())){
                    userApplyWxGroupMap.get(username.trim()).add(result.get("group_number").toString().trim());
                }else {
                    List<String> wxgroupnameList=new ArrayList<>();
                    wxgroupnameList.add(result.get("group_number").toString().trim());
                    userApplyWxGroupMap.put(username.trim(),wxgroupnameList);
                }
            }
        }
        //4.查询可独立发送的群 --删除被邀请的群
        for (Map.Entry<String, List<String>> entry : userAllWxGroupMap.entrySet()) {
            String username = entry.getKey().toString().trim();
            List groupNameList = entry.getValue() ;
            List needRemoveList=userApplyWxGroupMap.get(username);
            if (needRemoveList!=null&&needRemoveList.size()>0){
                for (int i=0;i<needRemoveList.size();i++){
                    groupNameList.remove(needRemoveList.get(i));
                }
            }
        }


        //5 获取可发送群只有一个账号群
        //key 群名  value为可发送的用户集合
        Map<String,List<String>> wxgrop_name_Map=new HashMap<>();
        for (Map.Entry<String, List<String>> entry : userAllWxGroupMap.entrySet()) {
            String username = entry.getKey().toString().trim();
            List groupNameList = entry.getValue() ;
            if (groupNameList!=null&&groupNameList.size()>0){
                for (int p=0;p<groupNameList.size();p++){
                   List<String> innerlist= wxgrop_name_Map.get(groupNameList.get(p).toString().trim());
                   if (innerlist!=null){
                       innerlist.add(username);
                   }else {
                       innerlist=new ArrayList<>();
                       innerlist.add(username);
                       wxgrop_name_Map.put(groupNameList.get(p).toString().trim(),innerlist);

                   }
                }
            }

        }
        //6.获取可发送是公众号名称
        List<String> gzhNameList=new ArrayList<>();
        List<Map<String, Object>> queryGzhList=jdbcTemplate.queryForList(" select   dict_value from sys_dict_data where status = '0' and dict_type = 'wx_gzh_type' order by dict_sort asc");
        if (queryGzhList!=null&&queryGzhList.size()>0){
            for (int i=0;i<queryGzhList.size();i++){
                String gzhName=queryGzhList.get(i).get("dict_value").toString();
                gzhNameList.add(gzhName);
            }
        }

        //获取每个群--每个成员--每个公众号最后的发送时间。


        //7 获取可发送群只有一个账号群



        //7.获取可发送群  账号数量 小于可发送公众号数量


        //7.获取可发送群  账号数量  等于可发送公众号数量

        //8.获取可发送群  账号数量大于可发送公众号数量

        //5 查询每个群 每个人最后发送时间
        List<Map<String, Object>> queryLastSendList=jdbcTemplate.queryForList(" SELECT  group_number,member,  create_time FROM sys_send_task_detail  " +
                " where id in( SELECT max(id) id   FROM sys_send_task_detail GROUP BY group_number,member)");
        if (queryLastSendList!=null&&queryLastSendList.size()>0){
            for (int i=0;i<queryLastSendList.size();i++){
                Map<String, Object> result=queryLastSendList.get(i);
                String username= (String) result.get("member");
                if (sendRecordMap.containsKey(username.trim())){
                    Map<String, Date>  tt=    sendRecordMap.get(username);
                    tt.put(result.get("group_number").toString().trim(),customFormateDate ((LocalDateTime) result.get("create_time")) );

                }else {
                    Map<String, Date> tt=new HashMap<>();
                     tt.put(result.get("group_number").toString().trim(),customFormateDate ((LocalDateTime) result.get("create_time")) );
                    sendRecordMap.put(username,tt);
                }
            }
        }


        //6 根据级别  判断该成员是否可以发送
        for (Map.Entry<String, List<String>> entry : userAllWxGroupMap.entrySet()) {
            String username = entry.getKey().toString().trim();
            List innergroupNameList = entry.getValue() ;
            Map<String, Date>  lastSendDate= sendRecordMap.get(username);
            if (innergroupNameList!=null&&innergroupNameList.size()>0&&lastSendDate!=null){
                Iterator<String> iterator = innergroupNameList.iterator();
                while (iterator.hasNext()) {
                    String groupname = iterator.next();
                    String level=   wxgroupLevelMap.get(groupname);
                    Date lastDate=lastSendDate.get(groupname);
                    if (!isNeedSend(lastDate,level)){
                        //移除
                        iterator.remove();
                    }
                }
            }
        }

        // 可以发送的集合
        //7.查询 每个群已经发送到记录
                List<Map<String, Object>>  wxgroupSendRecordResul=jdbcTemplate.queryForList("   SELECT member ,create_time,group_number,sendtimetype,brand_type,gzhtype " +
                        " FROM sys_send_task_detail w " +
                        ",(SELECT  MAX(id) id  FROM sys_send_task_detail GROUP BY gzhtype ,group_number)t " +
                        " where w.id=t.id ORDER BY w.group_number ,w.id asc");
        //每个群发送记录 key-群组  value为记录集合  记录该群已经有几个公众号被发送过/  哪几个人发送过  还有才是记录

        Map<String, Map<String,Object>>  wxgroupSendRecordMap=new HashMap<>();

        if (wxgroupSendRecordResul!=null&&wxgroupSendRecordResul.size()>0){
            for (int i=0;i<wxgroupSendRecordResul.size();i++){
                Map<String, Object> result=wxgroupSendRecordResul.get(i);
                String group_number= (String) result.get("group_number");
                String gzhtype= (String) result.get("gzhtype");
                String member= (String) result.get("member");
                Map<String,String> innermap=new HashMap<>();
                innermap.put(gzhtype,member);
                if (wxgroupSendRecordMap.containsKey(group_number.trim())){
                    Map<String,Object> t= wxgroupSendRecordMap.get(group_number.trim());
                    List<String> sendUsernameList= (List<String>) t.get("member");
                    List<String> sendGzhtypeList= (List<String>) t.get("gzhtype");
                    if (!sendUsernameList.contains(member)){
                        sendUsernameList.add(member);
                    }
                    if (!sendGzhtypeList.contains(gzhtype)){
                        sendGzhtypeList.add(gzhtype);
                    }
                    List<Map<String,String>>  sendInfoList= (List<Map<String, String>>) t.get("sendinfo");
                    sendInfoList.add(innermap);
                }else {
                    Map<String,Object> map= new HashMap<>();
                    List<String> sendUsernameList= new ArrayList<>();
                    List<String> sendGzhtypeList=  new ArrayList<>();
                        sendUsernameList.add(member);
                    map.put("member",sendUsernameList);
                        sendGzhtypeList.add(gzhtype);
                    map.put("gzhtype",sendGzhtypeList);
                    List<Map<String,String>>  sendInfoList= new ArrayList<>();
                    sendInfoList.add(innermap);
                    map.put("sendinfo",sendInfoList);

                    wxgroupSendRecordMap.put(group_number.trim(),map);
                }
            }
        }

        Map<String, Map<String,Object>> nowNeedSendMap=new HashMap<>();

        //8 开始计算发送 哪个公众号
        for (Map.Entry<String, List<String>> entry : userAllWxGroupMap.entrySet()) {
            String username = entry.getKey().toString().trim();
            List groupNameList = entry.getValue() ;
            if (groupNameList!=null&&groupNameList.size()>0){
                Iterator<String> iterator = groupNameList.iterator();
                while (iterator.hasNext()) {
                    String groupname = iterator.next();
                    //获取  该群中可以发送的成员名单
                  List<String> innerAllusrList=  wxgrop_name_Map.get(groupname);
                    //获取改群发送记录
                    Map<String,Object>  sendRecordMap3=wxgroupSendRecordMap.get(groupname);
                    if (sendRecordMap3==null){
                        sendRecordMap3=new HashMap<>();
                    }
                    List<String> needUserList=stringListCha(innerAllusrList,   sendRecordMap3.get("member"));
                    List<String> needGzhtypeList=stringListCha(gzhNameList,  sendRecordMap3.get("gzhtype"));
                    Map<String,Object>  needSen=  nowNeedSendMap.get(groupname);
                    if (needSen==null){
                        needSen=new HashMap<>();
                        nowNeedSendMap.put(groupname,needSen);
                    }
//                    List<String> nowuseList=stringListCha(innerAllusrList, (List<String>) sendRecordMap3.get("member"));
//                    List<String>  nowGzhtypeList=stringListCha(gzhNameList, (List<String>) sendRecordMap3.get("gzhtype"));
                    List<String> nowuseList= new ArrayList<>();
                    List<String> nowGzhtypeList= new ArrayList<>();
                    List<Map<String,String>>  sendInfoList= new ArrayList<>();
                    if (needSen.get("sendinfo")!=null){
                        sendInfoList= (List<Map<String, String>>) needSen.get("sendinfo");
                    }else {
                        needSen.put("sendinfo",sendInfoList);
                    }
                    if (needSen.get("member")!=null){
                         nowuseList= (List<String>) needSen.get("member");
                    }else {
                        needSen.put("member",nowuseList);
                    }
                    if (needSen.get("gzhtype")!=null){
                        nowGzhtypeList=  (List<String>) needSen.get("gzhtype") ;
                    }else {
                       needSen.put("gzhtype",nowGzhtypeList) ;
                    }
                    if (needUserList.contains(username)){
                        //两种情况  1没发过  2轮不到自己发
                        if (needGzhtypeList!=null&&needGzhtypeList.size()>0){
                            //排除掉已经发送的  。随机找一个
                             List<String>faa=stringListCha(needGzhtypeList,nowGzhtypeList);
                             if (faa!=null&&faa.size()>0){
                                 //随便发一个--
                                 nowGzhtypeList.add(faa.get(0));
                                 nowuseList.add(username);
                                 Map<String,String> innermap=new HashMap<>();
                                 innermap.put(faa.get(0),username);
                                 sendInfoList.add(innermap);

                             }else {
                                 //查询有没有存在一个人发了两个公众号的  如果有  则需要让出来,  1得给原来的号最少留一个  2
                                 List<String> fad=getCanSenGZHFromRecord(  sendRecordMap3.get("sendinfo"),nowuseList);
                                 //排除掉已经发送的  。随机找一个
                                 List<String>faa3=stringListCha(fad,nowGzhtypeList);
                                 if (faa3!=null&&faa3.size()>0){
                                     //随便发一个--
                                     nowGzhtypeList.add(faa3.get(faa3.size()-1));
                                     nowuseList.add(username);
                                     Map<String,String> innermap=new HashMap<>();
                                     innermap.put(faa3.get(faa3.size()-1),username);
                                     sendInfoList.add(innermap);

                                 }
                             }
                        }else {
                            //查询有没有存在一个人发了两个公众号的  如果有  则需要让出来
                            List<String> fad=getCanSenGZHFromRecord(sendRecordMap3.get("sendinfo"),nowuseList);
                            //排除掉已经发送的  。随机找一个
                            List<String>faa3=stringListCha(fad,nowGzhtypeList);
                            if (faa3!=null&&faa3.size()>0){
                                //随便发一个--
                                nowGzhtypeList.add(faa3.get(faa3.size()-1));
                                nowuseList.add(username);
                                Map<String,String> innermap=new HashMap<>();
                                innermap.put(faa3.get(faa3.size()-1),username);
                                sendInfoList.add(innermap);

                            }
                        }
                    }else {//老成员  需要发送新号
                        //新号优先发----
                        List<String>faa=stringListCha(needGzhtypeList,nowGzhtypeList);
                        if (needGzhtypeList!=null&&needGzhtypeList.size()>0&&faa!=null&&faa.size()>0){
                                //随便发一个--
                                nowGzhtypeList.add(faa.get(0));
                                nowuseList.add(username);
                                Map<String,String> innermap=new HashMap<>();
                                innermap.put(faa.get(0),username);
                                sendInfoList.add(innermap);
                        }else {
                            //取最晚发的那个记录再发
                            List<String> fad=getSendRecordByuser((List<Map<String, String>>) sendRecordMap3.get("sendinfo"),username);
                            List<String>faa3=stringListCha(fad,nowGzhtypeList);
                            if (faa3!=null&&faa3.size()>0){
                                //随便发一个--
                                nowGzhtypeList.add(faa3.get(faa3.size()-1));
                                nowuseList.add(username);
                                Map<String,String> innermap=new HashMap<>();
                                innermap.put(faa3.get(faa3.size()-1),username);
                                sendInfoList.add(innermap);

                            }
                        }

                    }



                }
            }
        }
//获取此次发送的  群组及集合--  插入总氮

        SysSendTask sysSendTask=new SysSendTask();
        sysSendTaskService.insertSysSendTask(sysSendTask);
        Long taskid=sysSendTask.getId();

        List<SysSendTaskDetail> sysSendTaskDetails=new ArrayList<>();
        for (Map.Entry<String, Map<String,Object>> entry : nowNeedSendMap.entrySet()) {
            String groupName = entry.getKey().toString().trim();
            Map<String,Object> innerMap = entry.getValue() ;
            if (innerMap.get("sendinfo")!=null){
                List<Map<String,String>>  sendInfoList= (List<Map<String, String>>) innerMap.get("sendinfo");
                for (int p=0;p<sendInfoList.size();p++){
                    Map<String,String> ffmap=sendInfoList.get(p);
                    for (Map.Entry<String, String> entry1 : ffmap.entrySet()) {
                        SysSendTaskDetail detail=new SysSendTaskDetail();
                        String gzhname = entry1.getKey().toString().trim();
                        String usename = entry1.getValue() .toString().trim();
                        detail.setSendtaskid(taskid);
                        detail.setGzhtype(gzhname);
                        detail.setMember(usename);
                        detail.setGroupNumber(groupName);
                        sysSendTaskDetails.add(detail);
                    }
                }
            }

        }

        //梳理好人之后
        batchInsertTaskDetail(sysSendTaskDetails,jdbcTemplate);
        System.out.println("完成了-----------"+nowNeedSendMap);
        return false;
    }

    @Override
    public void deleteHistoryData() throws Exception {
        /**
         * 发送记录保留10天发送数据
         */
       jdbcTemplate.execute(" DELETE FROM sys_send_task_detail where create_time<date_sub(now(), interval 11 day) ");
       jdbcTemplate.execute(" DELETE FROM sys_send_task where create_time<date_sub(now(), interval 11 day) ");
        /**
         * 清除日志表
         */
        jdbcTemplate.execute(" DELETE FROM sys_oper_log where oper_time<date_sub(now(), interval 11 day) ");
        jdbcTemplate.execute(" DELETE FROM sys_job_log where create_time<date_sub(now(), interval 11 day) ");

    }

    @Override
    public void resetTodayWxContentData() throws Exception {
        jdbcTemplate.execute("update sys_content set `status`=0 where status=1 and  to_days(createdate) = to_days(now()) ");

    }


    @Override
    public   List<Map<String, Object>> deleteStep1() throws Exception {
        /**
         * 定期清理邀请记录--并且已经通过的，查询邀请人是否还在，如果在则继续，不在的话 就删除
         *
         */
        return  jdbcTemplate.queryForList("  select attribute1, member,group_number ,groupid  from sys_wxapply_record  WHERE    attribute1 is not null  and status=0  ");

    }


    @Override
    public  void deleteStep2(Map<String, Object> map) throws Exception {
        String yqrmember= (String) map.get("attribute1");
        int groupid= (int) map.get("groupid");
     List tt=   jdbcTemplate.queryForList(" SELECT 1 FROM sys_wx_group where    FIND_IN_SET('"+yqrmember+"',member) and id= "+groupid);
     if (tt!=null&&tt.size()>0){

     }else {
         //邀请人为空了，将该邀请人加入记录删除掉
         jdbcTemplate.execute(" DELETE FROM   sys_wxapply_record where groupid="+groupid+" and member='"+yqrmember+"'");

         //随机找一条  已经通过的
         List<Map<String, Object>> ttmap=   jdbcTemplate.queryForList("  select attribute1, member,group_number ,groupid  from sys_wxapply_record  WHERE    status=0 and  groupid="+groupid+" and   attribute1 ='"+yqrmember+"'");
         if (ttmap!=null&&ttmap.size()>0){
             for (int i=0;i<ttmap.size();i++){
                 Map<String, Object> innermap=ttmap.get(i);
                 String inneryqr= (String) innermap.get("member");
                 List tt1=   jdbcTemplate.queryForList(" SELECT 1 FROM sys_wx_group where    FIND_IN_SET('"+inneryqr+"',member) and id= "+groupid);
                 if (tt1!=null&&tt1.size()>0){
                    //表示存在，可以用，此时将
                     //邀请人为空了，将该邀请人加入记录删除掉
                     jdbcTemplate.execute("update  sys_wxapply_record set   attribute1 =null where groupid="+groupid+" and member='"+inneryqr+"'");
                     //将其他邀请人改为本人
                     jdbcTemplate.execute(" update  sys_wxapply_record set   attribute1 ='"+inneryqr+"' where groupid="+groupid+" and attribute1='"+yqrmember+"'");
                     break;
                 }else {
                     //不存在 则需要删除掉
                     jdbcTemplate.execute("delete from   sys_wxapply_record   where groupid="+groupid+" and member='"+inneryqr+"'");
                 }

             }


         }

     }


    }
    /**
     * 很活跃--频率1日一次
     * 活跃  2日一次
     * 一般 4日一次
     * 很不活跃 7日一次
     * @param date
     * @param level
     * @return
     */
    public boolean isNeedSend(Date date, String level) throws Exception {
        if (date == null) {
            return true;
        }
        int bzdat = 0;
        int days = dateCha(date);
        if (level.equals("很活跃")) {
            bzdat = 1;
        } else if (level.equals("活跃")) {
            bzdat = 2;
        } else if (level.equals("一般")) {
            bzdat = 4;
        } else if (level.equals("很不活跃")) {
            bzdat = 7;
        }
        if (days>=bzdat){
            return true;
        }
        return false;
    }


    public int dateCha(Date startdate) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

           String startString = sdf.format(startdate);
            String endString = sdf.format(new java.util.Date());
              startdate = (Date) sdf.parse(startString);
             Date  enddate = (Date) sdf.parse(endString);
            //比较天数
         return (int) ((enddate.getTime()-startdate.getTime())/(24*60*60*1000));

    }

    /**
     *获取没有发送的公众号 和人员
     * @param allData
     * @param ooo
     * @return
     */
    public List<String> stringListCha(List<String> allData,Object ooo)  {
        if (ooo==null){
            return allData;
        }
        List<String> usedData = (List<String>) ooo;
        List<String> result=new ArrayList<>();
        if (allData!=null){
            for (int i=0;i<allData.size();i++){
                if (!usedData.contains(allData.get(i))){
                    result.add(allData.get(i));
                }
            }
        }else {
            return null;
        }
        return result;

    }

    /**
     *返回需要发送的公众号，如果空 表示不需要
     * 筛选 发送记录，查出一个用户发多次的公众号  --如果有新人进来，可以发送了就
     * @return
     */
    public List<String> getCanSenGZHFromRecord( Object ooo,   List<String> nowSendNameList )  {
        if (ooo==null){
            return new ArrayList<>();
        }
        List<Map<String,String>>sendInfoList = (List<Map<String, String>>) ooo;
        List<String> nameList=new ArrayList<>();
        List<String> retrunGzhList=new ArrayList<>();
        for (int i=0;i<sendInfoList.size();i++){
            for (Map.Entry<String,String> entry : sendInfoList.get(i).entrySet()) {
                String gzhtype = entry.getKey().toString().trim();
                String member = entry.getValue() .toString().trim();

                if (nameList.contains(member)){
                    retrunGzhList.add(gzhtype);
                }else {
                    if (nowSendNameList.contains(member)){//如果已发送的成员中包含  本人，则全部增加上
                        retrunGzhList.add(gzhtype);
                    }
                    nameList.add(member);
                }

            }
        }
        if (retrunGzhList.size()==0){
            return null;
        }
        return retrunGzhList;

    }

    /**
     *返回需要发送的公众号，如果空 表示不需要
     * 筛选 发送记录，查出一个用户发多次的公众号  --如果有新人进来，可以发送了就
     * @return
     */
    public List<String> getSendRecordByuser( List<Map<String,String>>sendInfoList,String username )  {
        List<String> retrunGzhList=new ArrayList<>();
        for (int i=0;i<sendInfoList.size();i++){
            for (Map.Entry<String,String> entry : sendInfoList.get(i).entrySet()) {
                String gzhtype = entry.getKey().toString().trim();
                String member = entry.getValue() .toString().trim();
                if (member.equals(username)){
                    retrunGzhList.add(gzhtype);
                }
            }
        }
        if (retrunGzhList.size()==0){
            return null;
        }
        return retrunGzhList;

    }

    /**
     * 批量插入发送记录表
     * @param tblStockOrderItemBarcodes
     * @param jdbcTemplate
     * @return
     */
    public int batchInsertTaskDetail(List<SysSendTaskDetail> tblStockOrderItemBarcodes, JdbcTemplate jdbcTemplate) {
        String insertStockOrderItemBarcodeSql = "INSERT INTO sys_send_task_detail (gzhtype, group_number,member, sendtimetype,sendtaskid) VALUES  (?, ?, ?, ?, ?)";
        int[] updateCountArray = jdbcTemplate.batchUpdate(insertStockOrderItemBarcodeSql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1, tblStockOrderItemBarcodes.get(i).getGzhtype());
                ps.setString(2, tblStockOrderItemBarcodes.get(i).getGroupNumber());
                ps.setString(3, tblStockOrderItemBarcodes.get(i).getMember());
                ps.setString(4, tblStockOrderItemBarcodes.get(i).getSendtimetype());
                ps.setLong(5, tblStockOrderItemBarcodes.get(i).getSendtaskid());
            }
            @Override
            public int getBatchSize() {
                return tblStockOrderItemBarcodes.size();
            }
        });
        int sumInsertedCount = 0;
        for (int a : updateCountArray) {
            sumInsertedCount += a;
        }
        return sumInsertedCount;
    }

    /**
     * 数据库时间转为当前时间
     * @param localDateTime
     * @return
     */
    public Date customFormateDate( LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        return  (Date) Date.from(zdt.toInstant());
    }
    @Override
    public   List<Map<String, Object>> resetHistoryContentToNowStep1() throws Exception {
        /**
         * 定期清理邀请记录--并且已经通过的，查询邀请人是否还在，如果在则继续，不在的话 就删除
         *
         */
        return  jdbcTemplate.queryForList("  select 1   FROM  sys_content   where    to_days(createdate) = to_days(now()) ");

    }

    @Override
    public void resetHistoryContentToNowStep2() throws Exception {
     // 默认查询40-60天谴的数据
        List<Map<String, Object>>  canResetDataList=  jdbcTemplate.queryForList("   select contentid,revert_count   FROM  sys_content   where     createdate<date_sub(now(), interval 40 day)  and createdate>  date_sub(now(), interval 60 day) " +
                " ORDER BY revert_count asc , createdate asc   limit 0,13") ;
        if (canResetDataList!=null&&canResetDataList.size()>0){
            int tt=canResetDataList.size();
            for (int i=0;i<3;i++){
                Random random = new Random();
               int jiaobiaio= random.nextInt(tt);
                Map<String, Object> innerMap=canResetDataList.get(jiaobiaio);
                int contentid= (int) innerMap.get("contentid");
                int revert_count= (int) innerMap.get("revert_count");
                int newcont=revert_count+1;
                jdbcTemplate.execute(" update  sys_content set  createdate=NOW(), revert_count ="+newcont+" where contentid="+contentid);
                System.out.println("重置更新了------"+contentid);

            }


        }


    }

    @Override
    public Date getNextGenxinDate() throws Exception {
        //去状态为最大时间
        List<Map<String, Object>>  list=    jdbcTemplate.queryForList("SELECT MAX(createdate)  dd FROM sys_content where    `status`=1  and   createdate<date_add(now(), interval 180 day) and createdate>  date_add(now(), interval 1 day) and content_type !='13'\n ");
        Date maxTime=new Date();
      if (list!=null&&list.size()>0){
          if ( list.get(0).get("dd")!=null){
              java.time.LocalDateTime    ee=(java.time.LocalDateTime)list.get(0).get("dd");
              maxTime= Date.from(ee.atZone(ZoneId.systemDefault()).toInstant());
          }
      }
        // 创建一个Date对象
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(maxTime);
        // 给日期加一天
        calendar.add(Calendar.DATE, 1);
        // 从Calendar对象获取新的Date对象
        return calendar.getTime();
    }

    @Override
    public List<Long> get15DaysNeedData() throws Exception {
        List<Long> ids=new ArrayList<>();
        /**
         * 第一步确保得有15天的数据，如果不够十五天则停止。
         */
        List<Map<String, Object>>  list2=    jdbcTemplate.queryForList(  "SELECT  distinct createdate FROM sys_content  where  `status`=1   " +
                "and createdate>date_add(now(), interval 179 day) and content_type !='13' "  );
        if (list2!=null&&list2.size()>14){//有十五天数据
            List<Map<String, Object>>  list=    jdbcTemplate.queryForList(  "SELECT contentid ,createdate  FROM sys_content  where  `status`=1   " +
                    "and createdate>date_add(now(), interval 179 day) and content_type !='13' " +
                    "and createdate <(SELECT  DATE_ADD(MIN(createdate), INTERVAL 15 DAY)  " +
                    "  FROM sys_content  where  `status`=1   and createdate>date_add(now(), interval 179 day) and content_type !='13')");

            if (list!=null&&list.size()>0){
                for (int i=0;i<list.size();i++){
                    Long id= Long.parseLong( list.get(i).get("contentid")+"") ;
                    ids.add(id);
                }
            }
        }

        return ids;
    }

    @Override
    public void updateContentDate(List<Long> list,Date date, int i) throws Exception {
        // 创建一个Date对象
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 给日期加一天
        calendar.add(Calendar.DATE, i);
        Date nowDate=  calendar.getTime();
        String insertStockOrderItemBarcodeSql = "update sys_content set createdate = ? where contentid = ? ";
        int[] updateCountArray = jdbcTemplate.batchUpdate(insertStockOrderItemBarcodeSql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setDate(1,  new java.sql.Date(nowDate.getTime())  );
                ps.setLong(2, list.get(i) );
            }
            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
    }
}
